import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        generateCode(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String code = req.getParameter("vcode");

        System.out.println("收到用户名：" + uname);
        System.out.println("收到密码：" + pwd);
        System.out.println("收到验证码：" + code);

        // 假设注册成功
        boolean isRegistered = true; // 这里可以根据实际业务逻辑判断是否注册成功

        if (isRegistered) {
            // 注册成功后跳转到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
        } else {
            // 注册失败，返回注册页面并显示错误信息
            req.setAttribute("msg", "注册失败，请重试");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }

    private void generateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();
        char sc = 'a';
        for (int i = 0; i <= 4; ++i) {
            int str = random.nextInt(62);
            if (str < 10) {
                sb.append(str);
            } else if (str < 36) {
                sc = (char) ((str - 10) + 'a');
                sb.append(sc);
            } else {
                sc = (char) ((str - 10) + 'A');
                sb.append(sc);
            }
        }
        BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.GRAY);
        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font("time", Font.BOLD, 18));
        graphics.drawString(sb.toString(), 3, 17);
        graphics.dispose();
        ImageIO.write(image, "JPG", response.getOutputStream());
        System.out.println("生成的验证码：" + sb);
        request.getSession().setAttribute("code", sb.toString());
    }
}